﻿namespace Digitalmes.Core.Configuration;

/// <summary>
/// Assets 资产配置文件帮助类。
/// </summary>
/// <remarks>
/// 注意：配置文件编码格式须为 UTF-8 格式，不能为 ASCII、UTF-8 BOM 等格式。
/// </remarks>
public static class AssetsConfigHelper
{
    /// <summary>
    /// 从指定的文件中提取配置数据。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName">配置文件</param>
    /// <returns>若不存在数据则返回默认值。</returns>
    public static T? Get<T>(string fileName)
        where T : class
    {
        var path = Path.Combine(AssetsConstants.AssetsConfigurationDirectory, fileName);
        if (Path.Exists(path))
        {
            var content = File.ReadAllText(path);
            return content.FromJson<T>();
        }

        return default;
    }

    /// <summary>
    /// 从指定的文件中提取配置数据。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName">配置文件</param>
    /// <returns>若不存在数据则返回默认值。</returns>
    public static Task<T?> GetAsync<T>(string fileName, CancellationToken cancellationToken = default)
       where T : class
    {
        TaskCompletionSource<T?> tcs = new();

        var path = Path.Combine(AssetsConstants.AssetsConfigurationDirectory, fileName);
        if (Path.Exists(path))
        {
            // File.ReadAllTextAsync() 方法会导致线程阻塞，Debug 调试进入方法内部后会正常执行，猜测是否是因为采用 HostedService 调用所致？
            // await File.ReadAllTextAsync(path, cancellationToken);

            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                var content = File.ReadAllText(path);
                tcs.SetResult(content.FromJson<T>());
            }
            catch (Exception ex) when (ex is OperationCanceledException)
            {
                tcs.SetCanceled(cancellationToken);
            }
            catch (Exception ex)
            {
                tcs.SetException(ex);
            }
        }
        else
        {
            tcs.SetResult(default);
        }

        return tcs.Task;
    }
}
